package mymap.utils.image;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageUtils {

	/**
	 * Redimenciona uma imagem
	 * 
	 * @param img
	 * @param newW
	 * @param newH
	 * @return
	 */
	public static BufferedImage resize(BufferedImage img, int newW, int newH) {
		int w = img.getWidth();
		int h = img.getHeight();
		BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
		Graphics2D g = dimg.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
		g.dispose();
		return dimg;
	}
	
	public static BufferedImage toBufferedImage(Image image){
		BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
				image.getHeight(null), BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = bufferedImage.createGraphics();
		g2.drawImage(image, null, null);
		return bufferedImage;
	}

	/**
	 * Redimenciona imagem com base na largura
	 * 
	 * @param img
	 * @param newW
	 * @return
	 */
	public static BufferedImage resize(BufferedImage img, int newW) {
		double proporcao = new Double(newW) / img.getWidth();
		int h = new Double(img.getHeight() * proporcao).intValue();
		return resize(img, newW, h);
	}

	/**
	 * Salva a imagem com o nome especificado dentro da pasta especificada Caso
	 * o diretorio não exita, cria o mesmo. OBS.: É necessário usar extensao do
	 * arquivo
	 * 
	 * @param image
	 * @param fileName
	 * @return path da imagem
	 * @throws IOException
	 */
	public static File storeImage(Image image, String dir, String fileName,
			String fileType) throws IOException {

		File imageDir = new File(dir);
		if (!imageDir.exists())
			imageDir.mkdir();

		// String imageFileName = fileName + "." + FILE_TYPE;

		BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
				image.getHeight(null), BufferedImage.TYPE_INT_RGB);

		Graphics2D g2 = bufferedImage.createGraphics();
		g2.drawImage(image, null, null);
		File imageFile = new File(imageDir, fileName);
		ImageIO.write(bufferedImage, fileType, imageFile);

		return imageFile;
	}

	public static BufferedImage joinImages(Image[][] imgVector, int quadroSize)
			throws IOException {
		int w = quadroSize * imgVector.length;
		int h = quadroSize * imgVector[0].length;

		BufferedImage image = new BufferedImage(w, h, Image.SCALE_DEFAULT);
		Graphics2D g2 = image.createGraphics();

		for (int i = 0; i < imgVector.length; i++) {
			for (int j = 0; j < imgVector[i].length; j++) {
				g2.drawImage(imgVector[i][j], quadroSize * i, quadroSize * j,
						null);
			}
		}

		g2.dispose();
		return image;
	}

}
